// 跳转到书籍详情页
function goToBookDetail(id) {
    window.location.href = `./jinwen-bookDetail.html?id=${id}`;
}

// 1. 基础配置：左侧榜单类型与rankType的映射关系
const rankTypeMap = {
    '全部榜单': null,      
    '畅销榜': 9,
    '点击榜': 10,
    '打赏榜': 11,
    '推荐榜': 12, // 推荐榜rankType固定为12
    '新书榜': 13,
    '更新榜': 14,
    '书评榜': 17,           
    '财神榜': 18
};

// 存储全部榜单数据（供顶部小型榜单使用）
let allRankingsData = null;

// 2. 初始加载：顶部小型榜单数据（页面加载时触发）
fetch("https://app2.motie.com/ranking/all?siteId=5", {
    headers: { 'os': 'pc' }
}).then(res => res.json())
.then(res1 => {
    allRankingsData = res1;
    renderAllRankings(); // 数据加载完成后渲染顶部榜单
})
.catch(err => {
    console.error('顶部榜单数据加载失败:', err);
});

// 3. 通用渲染函数：生成顶部小型榜单（支持标签切换）
function renderRanking(containerSelector, title, targetType, tabTypes = ['日', '周', '总']) {
    if (!allRankingsData) return;
    
    // 查找当前榜单对应的数据源
    const targetData = allRankingsData.data.find(item => item.type === targetType);
    if (!targetData) {
        console.warn(`未找到类型为${targetType}的顶部榜单数据`);
        return;
    }
    
    const container = document.querySelector(containerSelector);
    if (!container) {
        console.warn(`顶部榜单容器${containerSelector}未找到`);
        return;
    }
    
    // 生成标签HTML（推荐榜已改为['日', '月', '总']）
    const tabsHtml = tabTypes.map((tab, index) => 
        `<li class="${index === 0 ? 'on' : ''}">${tab}</li>`
    ).join('');
    
    // 渲染顶部榜单容器结构
    container.innerHTML = `
        <div class="listTab">
            <div class="listTitle">
                <div class="modtitle">
                    <div class="titlebd"><h2>${title}</h2></div>
                </div>
            </div>
            <ul class="tab-ul">${tabsHtml}</ul>
            <ul class="con-ul">
                <div class="listBox"><ul class="rank"></ul></div>
            </ul>
        </div>
    `;
    
    // 绑定标签切换事件
    const rankList = container.querySelector('.rank');
    const tabs = container.querySelectorAll('.tab-ul li');
    
    // 渲染榜单列表数据
    function renderListData(index) {
        rankList.innerHTML = '';
        if (!targetData.item || !targetData.item[index] || !targetData.item[index].content) {
            console.warn(`类型为${targetType}的${tabTypes[index]}榜数据缺失`);
            return;
        }
        
        // 循环渲染书籍项
        targetData.item[index].content.forEach((book, itemIndex) => {
            const li = document.createElement('li');
            if (itemIndex === 0) li.className = 'top';
            
            li.innerHTML = itemIndex === 0 
                ? `
                    <span class="num front">${itemIndex + 1}</span>
                    <div class="book-clock">
                        <img src="${book.bookIconUrl}" alt="${book.bookName}" onclick="goToBookDetail(${book.bookId})">
                        <div class="dd">
                            <p class="bookname" onclick="goToBookDetail(${book.bookId})">${book.bookName}</p>
                            <span class="book-author">作者：${book.authorName}</span>
                        </div>
                    </div>
                `
                : `
                    <span class="num front">${itemIndex + 1}</span>
                    <p class="book-list" onclick="goToBookDetail(${book.bookId})">${book.bookName}</p>
                `;
            rankList.appendChild(li);
        });
    }
    
    // 标签鼠标悬浮切换
    tabs.forEach((tab, index) => {
        tab.addEventListener('mouseenter', () => {
            tabs.forEach(t => t.classList.remove('on'));
            tab.classList.add('on');
            renderListData(index);
        });
    });
    
    // 初始渲染第一个标签数据
    renderListData(0);
}

// 4. 渲染所有顶部小型榜单：关键修改1：推荐榜标签改为['日', '月', '总']
function renderAllRankings() {
    renderRanking('.allRank', '畅销榜', 9, ['日', '周', '总']);
    renderRanking('.allRank2', '点击榜', 10, ['日', '周', '总']);
    renderRanking('.allRank3', '打赏榜', 11, ['日', '周', '总']);
    renderRanking('.allRank4', '推荐榜', 12, ['日', '月', '总']); // 推荐榜：周榜→月榜
    renderRanking('.allRank5', '书评榜', 17, ['周', '总']);
}

// 5. 页面DOM加载完成后：初始化左侧导航与右侧榜单切换
document.addEventListener('DOMContentLoaded', function() {
    // 获取核心DOM元素
    const leftItems = document.querySelectorAll('.container .rank .left a');
    const rightContainer = document.querySelector('.container .rank .right');
    const newRightContainer = document.querySelector('.container .rank .newright');
    const defaultRankContainer = document.querySelector('.defaultrank');
    const menuTabsContainer = document.querySelector('.container .rank .newright .menu .com');
    const menuTitleElement = document.querySelector('.container .rank .newright .menu .fl'); // 获取.menu .fl元素
    
    // 校验关键DOM元素
    if (!leftItems || !rightContainer || !newRightContainer || !defaultRankContainer || !menuTabsContainer || !menuTitleElement) {
        console.error('核心DOM元素缺失，榜单功能无法正常初始化');
        return;
    }
    
    let currentRankType = null; // 当前激活的榜单类型

    // 5.1 初始化默认视图
    function initDefaultView() {
        leftItems.forEach(item => item.classList.remove('on'));
        leftItems[0].classList.add('on');
        
        rightContainer.style.display = 'block';
        newRightContainer.style.display = 'none';
        
        // 初始化右侧.menu标签
        const defaultTabs = menuTabsContainer.querySelectorAll('li');
        if (defaultTabs.length >= 3) {
            defaultTabs[0].classList.add('on');
            defaultTabs.forEach(tab => tab.style.display = 'block');
        }
    }

    // 5.2 更新右侧.menu标签状态：同步更新菜单名称
    function updateTabStatus(activeTab, rankType, rankName) {
        // 更新.menu .fl的文字为当前榜单名称
        menuTitleElement.textContent = rankName;
        
        const tabs = menuTabsContainer.querySelectorAll('li');
        if (tabs.length < 3) return;
        
        // 重置标签状态与文本
        tabs.forEach(tab => {
            tab.classList.remove('on');
            const pTag = tab.querySelector('p') || document.createElement('p');
            if (!tab.querySelector('p')) tab.appendChild(pTag); // 确保有<p>元素，避免内容丢失
            pTag.textContent = '';
        });
        
        // 根据榜单类型设置标签
        switch(rankType) {
            case 12: // 推荐榜显示“日/月/总”
                tabs.forEach(tab => tab.style.display = 'block');
                tabs[0].querySelector('p').textContent = '日榜';
                tabs[1].querySelector('p').textContent = '月榜';
                tabs[2].querySelector('p').textContent = '总榜';
                break;
            case 17: // 书评榜：隐藏日榜
                tabs[0].style.display = 'none';
                tabs[1].style.display = 'block';
                tabs[2].style.display = 'block';
                tabs[1].querySelector('p').textContent = '周榜';
                tabs[2].querySelector('p').textContent = '总榜';
                break;
            default: // 其他榜单：保持“日/周/总”
                tabs.forEach(tab => tab.style.display = 'block');
                tabs[0].querySelector('p').textContent = '日榜';
                tabs[1].querySelector('p').textContent = '周榜';
                tabs[2].querySelector('p').textContent = '总榜';
                break;
        }
        
        // 激活当前标签
        if (activeTab) activeTab.classList.add('on');
    }

    // 5.3 封装右侧榜单数据请求与渲染
    function fetchRankData(group, rankType) {
        fetch(`https://app2.motie.com/ranking/detail?group=${group}&siteId=5&rankType=${rankType}&pageSize=30`, {
            headers: { 'os': 'pc' }
        })
        .then(res => res.json())
        .then(res1 => {
            defaultRankContainer.innerHTML = '';
            
            // 时间格式化工具函数
            function formatTime(timestamp) {
                if (typeof timestamp === 'string') timestamp = parseInt(timestamp);
                if (timestamp.toString().length > 10) timestamp = Math.floor(timestamp / 1000);
                const date = new Date(timestamp * 1000);
                return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
            }
            
            // 循环渲染右侧书籍详情列表
            if (res1.data && res1.data.length > 0) {
                res1.data.forEach((book, index) => {
                    const formattedTime = formatTime(book.lastChapterTime);
                    defaultRankContainer.innerHTML += `
                        <div class="finalList">
                            <div class="final">
                                <img src="${book.bookIconUrl}" alt="${book.bookName}" onclick="goToBookDetail(${book.bookId})">
                                <div class="middle">
                                    <a class="bigpic-book-name" onclick="goToBookDetail(${book.bookId})">
                                        <span class="num on">${index + 1}</span>${book.bookName}
                                    </a>
                                    <p>
                                        <a>${book.authorName}</a> | 
                                        <a>${book.categoryVO?.name || '未知分类'}</a> | 
                                        <a>${book.finish ? '已完结' : '连载中'}</a>
                                        <span class="click">${book.words} 总字数</span>
                                    </p>
                                    <p class="big-info">${book.introduce}</p>
                                    <p>
                                        <a class="red">最近更新：${book.lastChapterName}</a>
                                        <span>| ${formattedTime}</span>
                                    </p>
                                </div>
                                <div class="bigbtn">
                                    <div class="detailbtn" onclick="goToBookDetail(${book.bookId})">书籍详情</div>
                                    <div class="addtn">加入书架</div>
                                </div>
                            </div>
                        </div>
                    `;
                });
            }
        })
        .catch(err => {
            console.error(`榜单数据请求失败（group=${group}, rankType=${rankType}）:`, err);
            defaultRankContainer.innerHTML = '<p class="load-error">数据加载失败，请稍后重试</p>';
        });
    }

    // 5.4 绑定左侧导航点击事件：传递榜单名称更新菜单
    leftItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            const itemText = this.textContent.trim(); // 获取当前点击的榜单名称（如"畅销榜"）
            currentRankType = rankTypeMap[itemText];
            
            // 激活当前左侧导航项
            leftItems.forEach(navItem => navItem.classList.remove('on'));
            this.classList.add('on');
            
            // 获取右侧.menu的三个标签
            const dayTab = menuTabsContainer.querySelector('li:nth-child(1)');
            const monthOrWeekTab = menuTabsContainer.querySelector('li:nth-child(2)');
            const totalTab = menuTabsContainer.querySelector('li:nth-child(3)');
            
            // 切换显示：全部榜单 vs 具体榜单
            if (itemText === '全部榜单') {
                rightContainer.style.display = 'block';
                newRightContainer.style.display = 'none';
                renderAllRankings();
            } else {
                rightContainer.style.display = 'none';
                newRightContainer.style.display = 'block';
                
                // 日榜点击事件
                if (dayTab) {
                    dayTab.removeEventListener('click', dayTabHandler);
                    function dayTabHandler() {
                        // 传递当前榜单名称到updateTabStatus
                        updateTabStatus(dayTab, currentRankType, itemText);
                        fetchRankData(3, currentRankType);
                    }
                    dayTab.addEventListener('click', dayTabHandler);
                }
                
                // 月榜/周榜点击事件
                if (monthOrWeekTab) {
                    monthOrWeekTab.removeEventListener('click', monthWeekHandler);
                    function monthWeekHandler() {
                        updateTabStatus(monthOrWeekTab, currentRankType, itemText);
                        const targetGroup = currentRankType === 12 ? 4 : 1;
                        fetchRankData(targetGroup, currentRankType);
                    }
                    monthOrWeekTab.addEventListener('click', monthWeekHandler);
                }
                
                // 总榜点击事件
                if (totalTab) {
                    totalTab.removeEventListener('click', totalTabHandler);
                    function totalTabHandler() {
                        updateTabStatus(totalTab, currentRankType, itemText);
                        fetchRankData(2, currentRankType);
                    }
                    totalTab.addEventListener('click', totalTabHandler);
                }
                
                // 初始化默认标签状态
                if (currentRankType === 17) {
                    updateTabStatus(monthOrWeekTab, currentRankType, itemText);
                    fetchRankData(1, currentRankType);
                } else {
                    updateTabStatus(dayTab, currentRankType, itemText);
                    fetchRankData(3, currentRankType);
                }
            }
        });
    });

    // 5.5 初始化页面
    initDefaultView();
});